"""
配置管理模块
负责保存和加载程序配置，包括房间信息、用户设置等
"""
import json
import os
import socket
from pathlib import Path


class ConfigManager:
    """配置管理器"""
    
    def __init__(self):
        self.config_dir = Path.home() / ".walkietalkie"
        self.config_file = self.config_dir / "config.json"
        self.default_config = {
            "user_name": socket.gethostname(),
            "room_name": "",
            "room_host": "",
            "is_host": False,
            "auto_rejoin": False,
            "muted": False,
            "hotkey": "ctrl+alt+t",
            "hotkey_mode": "ptt",  # ptt=按住模式, toggle=切换模式
            "selected_ip": "",  # 用户选择的IP地址，为空则自动选择
            "theme": "light",
            "audio_codec": "pcm",
            "port": 9527,
            "last_members": [],  # 上次房间成员列表 [{"name": "xxx", "ip": "xxx"}, ...]
            "room_members": {},  # 房间成员字典 {room_name: [{"name": "xxx", "ip": "xxx"}, ...]}
            "auto_start": False,
            "close_to_tray": True,  # 关闭时最小化到托盘
        }
        self.config = self.default_config.copy()
        self._ensure_config_dir()
        self.load()
    
    def _ensure_config_dir(self):
        """确保配置目录存在"""
        if not self.config_dir.exists():
            self.config_dir.mkdir(parents=True, exist_ok=True)
    
    def load(self):
        """加载配置"""
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                    self.config.update(loaded_config)
            except Exception as e:
                print(f"加载配置失败: {e}")
                self.config = self.default_config.copy()
        else:
            self.config = self.default_config.copy()
    
    def save(self):
        """保存配置"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"保存配置失败: {e}")
    
    def get(self, key, default=None):
        """获取配置项"""
        return self.config.get(key, default)
    
    def set(self, key, value):
        """设置配置项"""
        self.config[key] = value
        self.save()
    
    def update(self, **kwargs):
        """批量更新配置"""
        self.config.update(kwargs)
        self.save()
    
    def reset(self):
        """重置配置为默认值"""
        self.config = self.default_config.copy()
        self.save()
    
    def save_room_members(self, room_name: str, members: list):
        """保存房间成员信息"""
        room_members = self.config.get("room_members", {})
        room_members[room_name] = members
        self.set("room_members", room_members)
        # 同时更新last_members
        self.set("last_members", members)
    
    def get_room_members(self, room_name: str):
        """获取房间成员信息"""
        room_members = self.config.get("room_members", {})
        return room_members.get(room_name, [])
    
    def clear_room_state(self):
        """清除房间状态"""
        self.update(
            room_name="",
            room_host="",
            is_host=False,
            last_members=[]
        )
    
    def get_local_ip(self):
        """获取本机局域网IP"""
        # 优先使用用户选择的IP
        selected_ip = self.config.get("selected_ip", "")
        if selected_ip:
            print(f"使用用户选择的IP: {selected_ip}")
            return selected_ip
        
        # 如果没有选择，则自动获取
        try:
            # 方法1：获取所有网络接口的IP地址
            import socket
            hostname = socket.gethostname()
            ip_list = socket.gethostbyname_ex(hostname)[2]
            
            # 过滤出局域网IP（排除127.0.0.1和虚拟网卡）
            lan_ips = []
            for ip in ip_list:
                if ip.startswith('192.168.') or ip.startswith('10.') or ip.startswith('172.'):
                    lan_ips.append(ip)
            
            # 优先返回192.168开头的IP
            for ip in lan_ips:
                if ip.startswith('192.168.'):
                    return ip
            
            # 其次返回10.开头的IP
            for ip in lan_ips:
                if ip.startswith('10.'):
                    return ip
            
            # 返回172.开头的IP
            if lan_ips:
                return lan_ips[0]
            
            # 方法2：如果上面的方法没找到，使用UDP连接方式
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except Exception as e:
            print(f"获取本机IP失败: {e}")
            return "127.0.0.1"

